package com.hmall.trade.listener;

import com.hmall.api.pay.PayClient;
import com.hmall.api.pay.dto.PayOrderDTO;
import com.hmall.common.constants.MqConstants;
import com.hmall.trade.service.IOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * TODO
 *
 * @Author mr.Du
 * @Date 2025/6/23 2025/6/23
 */
@Component
@Slf4j
public class PayFinishListener {

    @Autowired
    private PayClient payClient;

    @Autowired
    private IOrderService orderService;

   /* @Autowired
    private RedissonClient redissonClient;*/

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MqConstants.DELAY_ORDER_QUEUE_NAME),
            exchange = @Exchange(name = MqConstants.DELAY_EXCHANGE_NAME, delayed = "true", type = ExchangeTypes.DIRECT),
            key = MqConstants.DELAY_ORDER_KEY
    ))
    public void payFinishListener(Message message, Long orderId) {
        //查询订单
        PayOrderDTO payOrderDTO = payClient.queryPayOrderByBizOrderNo(orderId);
        //检查订单是否已支付
        if (payOrderDTO != null && payOrderDTO.getStatus() == 3) {
            //已支付,标记订单状态为已支付
            log.info("消费者监测到消息,订单已支付");
        }
        //未支付,业务幂等性判断,取消订单,回滚库存
        orderService.cancelOrder(orderId);
        log.info("消费者消费消息,订单已取消");
    /*    String correlationId = message.getMessageProperties().getCorrelationId();
        RLock lock = redissonClient.getLock(correlationId);
        lock.tryLock();
        try {
            // 取消订单
            orderService.cancelOrder(orderId);
        } finally {
            lock.unlock();
        }*/
    }
}
